package com.hanhai.material.device.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hanhai.material.common.result.DataLabel;
import com.hanhai.material.common.result.Result;
import com.hanhai.material.common.result.ResultTool;
import com.hanhai.material.device.entity.*;
import com.hanhai.material.device.model.ProductModel;
import com.hanhai.material.device.model.ProductRecordIntoModel;
import com.hanhai.material.device.service.*;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.relation.RelationManager;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import static com.hanhai.material.device.entity.table.SysBadRecordTableDef.SYS_BAD_RECORD;
import static com.hanhai.material.device.entity.table.SysProductRecordIntoTableDef.SYS_PRODUCT_RECORD_INTO;
import static com.hanhai.material.device.entity.table.SysProductRecordShiftTableDef.SYS_PRODUCT_RECORD_SHIFT;
import static com.hanhai.material.utils.TimeUtils.fromDateToString;
import static com.mybatisflex.core.query.QueryMethods.distinct;
import static com.mybatisflex.core.query.QueryMethods.sum;

/**
 * 控制层。
 *
 * @author youchuang
 * @since 2024/01/12 17:32:50
 */
@RestController
@RequestMapping("/sysProductRecordShift")
@Log4j2
public class SysProductRecordShiftController {

    @Autowired
    private SysProductRecordShiftService sysProductRecordShiftService;

    @Autowired
    private SysBadRecordService sysBadRecordService;
    @Autowired
    private SysProductRecordDetentionService sysProductRecordDetentionService;

    @Autowired
    private SysMachineAdjustRecordService sysMachineAdjustRecordService;

    /**
     * 添加。
     *
     * @param sysProductRecordShift
     * @return {@code true} 添加成功，{@code false} 添加失败
     */
    @PostMapping("save")
    public boolean save(@RequestBody SysProductRecordShift sysProductRecordShift) {
        return sysProductRecordShiftService.save(sysProductRecordShift);
    }

    /**
     * 根据主键删除。
     *
     * @param id 主键
     * @return {@code true} 删除成功，{@code false} 删除失败
     */
    @DeleteMapping("remove/{id}")
    public boolean remove(@PathVariable Serializable id) {
        return sysProductRecordShiftService.removeById(id);
    }

    /**
     * 根据主键更新。
     *
     * @param productModel
     * @return {@code true} 更新成功，{@code false} 更新失败
     */
    @PostMapping("update")
    public Result<?> update(@RequestBody ProductModel productModel) {
        log.error("生产记录填写：{}", JSON.toJSONString(productModel));

        if (productModel.getProductRecordShift() != null) {
            SysProductRecordShift sysProductRecordShift = productModel.getProductRecordShift();
            log.error("生产记录填写：{}", JSON.toJSONString(sysProductRecordShift));
            boolean result = this.sysProductRecordShiftService.updateById(sysProductRecordShift);
            if (result) {
                if (!productModel.getProductRecordDetentionList().isEmpty()) {
                    List<SysProductRecordDetention> addList = new ArrayList<>();
                    List<SysProductRecordDetention> updateList = new ArrayList<>();
                    for (SysProductRecordDetention productRecordDetention : productModel.getProductRecordDetentionList()) {
//                        QueryWrapper queryWrapper = QueryWrapper.create();
//                        queryWrapper.where(SYS_PRODUCT_RECORD_DETENTION.PRODUCT_RECORD_ID.eq(productRecordDetention.getProductRecordId()));
//                        queryWrapper.where(SYS_PRODUCT_RECORD_DETENTION.TYPE.eq(productRecordDetention.getType()));
//                        queryWrapper.where(SYS_PRODUCT_RECORD_DETENTION.REASON.eq(productRecordDetention.getReason()));
//                        queryWrapper.where(SYS_PRODUCT_RECORD_DETENTION.WORK_PLAN_ID.eq(productRecordDetention.getWorkPlanId()));
//                        queryWrapper.where(SYS_PRODUCT_RECORD_DETENTION.PRODUCT_DATE.eq(productRecordDetention.getProductDate()));
//                        queryWrapper.limit(1);
//                        SysProductRecordDetention sysProductRecordDetention = this.sysProductRecordDetentionService.getOne(queryWrapper);
                        if (productRecordDetention.getId() != null) {
                            productRecordDetention.setProductRecordId(sysProductRecordShift.getId());
                            if (productRecordDetention.getNum() == 0) {
                                productRecordDetention.setStatus(2);
                            } else {
                                productRecordDetention.setStatus(0);
                            }
                            updateList.add(productRecordDetention);
                        } else {
                            productRecordDetention.setMachineArea(sysProductRecordShift.getMachineArea());
                            productRecordDetention.setProductId(sysProductRecordShift.getProductId());
                            productRecordDetention.setProductName(sysProductRecordShift.getProductName());
                            productRecordDetention.setProductDate(sysProductRecordShift.getProductDate());
                            productRecordDetention.setShortName(sysProductRecordShift.getShortName());
                            productRecordDetention.setProductRecordId(sysProductRecordShift.getId());
                            productRecordDetention.setTotalCount(sysProductRecordShift.getTotalCount());
                            productRecordDetention.setWorkPlanId(sysProductRecordShift.getWorkPlanId());
                            productRecordDetention.setGoodNum(sysProductRecordShift.getGoodNum());
                            productRecordDetention.setBadNum(sysProductRecordShift.getBadNum());
                            productRecordDetention.setId(UUID.randomUUID().toString());
                            productRecordDetention.setMachineName(sysProductRecordShift.getMachineName());
                            productRecordDetention.setGroupName(sysProductRecordShift.getGroupName());
                            productRecordDetention.setShift(sysProductRecordShift.getShift());
                            if (productRecordDetention.getNum() == 0) {
                                productRecordDetention.setStatus(2);
                            } else {
                                productRecordDetention.setStatus(0);
                                productRecordDetention.setTotalNum(productRecordDetention.getNum());
                                addList.add(productRecordDetention);
                            }

                        }
                    }
                    this.sysProductRecordDetentionService.saveBatch(addList);
                    this.sysProductRecordDetentionService.updateBatch(updateList);
                }
                if (!productModel.getMachineAdjustRecordList().isEmpty()) {
                    List<SysMachineAdjustRecord> addList = new ArrayList<>();
                    List<SysMachineAdjustRecord> updateList = new ArrayList<>();
                    for (SysMachineAdjustRecord adjustRecord : productModel.getMachineAdjustRecordList()) {
                        if (adjustRecord.getDuration() > 0) {
                            if (adjustRecord.getId() == null) {
                                adjustRecord.setId(UUID.randomUUID().toString());
                                adjustRecord.setProductDate(sysProductRecordShift.getProductDate());
                                adjustRecord.setProductId(sysProductRecordShift.getProductId());
                                adjustRecord.setMachineName(sysProductRecordShift.getMachineName());
                                adjustRecord.setProductName(sysProductRecordShift.getProductName());
                                adjustRecord.setShift(sysProductRecordShift.getShift());
                                adjustRecord.setShiftCode(sysProductRecordShift.getShiftCode());
                                adjustRecord.setCreateUserId(sysProductRecordShift.getUpdateUserId());
                                adjustRecord.setCreateUserName(sysProductRecordShift.getUpdateUserName());
                                adjustRecord.setWorkPlanId(sysProductRecordShift.getWorkPlanId());
                                adjustRecord.setProductRecordShiftId(sysProductRecordShift.getId());
                                adjustRecord.setProductRecordId(sysProductRecordShift.getProductRecordId());
                                addList.add(adjustRecord);
                            } else {
                                updateList.add(adjustRecord);
                            }
                        }
                    }
                    this.sysMachineAdjustRecordService.saveBatch(addList);
                    this.sysMachineAdjustRecordService.updateBatch(updateList);
                }

            }

            return result ? ResultTool.success() : ResultTool.fail();
        } else {
            return ResultTool.fail();
        }

    }


    /**
     * 查询所有。
     *
     * @return 所有数据
     */
    @PostMapping("list")
    public Result<?> list(@RequestBody SysProductRecordShift sysProductRecordShift) {
        QueryWrapper queryWrapper = QueryWrapper.create();

        if (sysProductRecordShift.getMachineName() != null) {
            queryWrapper.where(SYS_PRODUCT_RECORD_SHIFT.MACHINE_NAME.eq(sysProductRecordShift.getMachineName()));
        }
        if (sysProductRecordShift.getShift() != null) {
            queryWrapper.where(SYS_PRODUCT_RECORD_SHIFT.SHIFT.eq(sysProductRecordShift.getShift()));
        }
        queryWrapper.where(SYS_PRODUCT_RECORD_SHIFT.PRODUCT_DATE.eq(fromDateToString("yyyy-MM-dd", sysProductRecordShift.getProductDate())));
        queryWrapper.orderBy(SYS_PRODUCT_RECORD_SHIFT.MACHINE_NAME, true);

        RelationManager.addIgnoreRelations("productRecordList");
        List<SysProductRecordShift> sysProductRecordShiftList = this.sysProductRecordShiftService.getMapper().selectListWithRelationsByQuery(queryWrapper);
        for (SysProductRecordShift sysProductRecordShift1 : sysProductRecordShiftList) {
            queryWrapper = QueryWrapper.create();
            queryWrapper.where(SYS_BAD_RECORD.WORK_PLAN_ID.eq(sysProductRecordShift1.getWorkPlanId()));
            queryWrapper.where(SYS_BAD_RECORD.SHIFT.eq(sysProductRecordShift1.getShift()));
            queryWrapper.select(SYS_BAD_RECORD.REASON_TYPE, sum(SYS_BAD_RECORD.NUM).as("num"));
            queryWrapper.groupBy(SYS_BAD_RECORD.WORK_PLAN_ID, SYS_BAD_RECORD.REASON_TYPE);
            List<SysBadRecord> badRecordList = this.sysBadRecordService.list(queryWrapper);
            log.error("BadRecordList：{}", badRecordList);
            for (SysBadRecord sysBadRecord : badRecordList) {
                switch (sysBadRecord.getReasonType()) {
                    case "调机不良":
                        sysProductRecordShift1.setTjbl(sysBadRecord.getNum());
                        break;
                    case "自动化不良":
                        sysProductRecordShift1.setZdhbl(sysBadRecord.getNum());
                        break;
                    case "制程不良":
                        sysProductRecordShift1.setZcbl(sysBadRecord.getNum());
                        break;
                    case "来料不良":
                        sysProductRecordShift1.setLlbl(sysBadRecord.getNum());
                        break;
                    case "其他不良":
                        sysProductRecordShift1.setQtbl(sysBadRecord.getNum());
                        break;
                    case "品质领取":
                        sysProductRecordShift1.setPzlq(sysBadRecord.getNum());
                        break;
                    default:
                        break;
                }
                queryWrapper = QueryWrapper.create();
                queryWrapper.where(SYS_BAD_RECORD.WORK_PLAN_ID.eq(sysProductRecordShift1.getWorkPlanId()));
                queryWrapper.where(SYS_BAD_RECORD.SHIFT.eq(sysProductRecordShift1.getShift()));
                queryWrapper.where(SYS_BAD_RECORD.REASON_TYPE.eq(sysBadRecord.getReasonType()));
                queryWrapper.select(SYS_BAD_RECORD.REASON_NAME, sum(SYS_BAD_RECORD.NUM).as("num"));
                queryWrapper.groupBy(SYS_BAD_RECORD.WORK_PLAN_ID, SYS_BAD_RECORD.REASON_NAME);
                List<SysBadRecord> badRecordList1 = this.sysBadRecordService.list(queryWrapper);
                sysBadRecord.setBadRecordList(badRecordList1);
            }
            sysProductRecordShift1.setBadRecordList(badRecordList);
        }

        return sysProductRecordShiftList.isEmpty() ? ResultTool.fail() : ResultTool.success(sysProductRecordShiftList);
    }

    @Autowired
    SysMachinePlcService sysMachinePlcService;

    @PostMapping("/listByCondition")
    public Result<?> getListByCondition(@RequestBody SysProductRecordShift sysProductRecordShift) {
        QueryWrapper queryWrapper = QueryWrapper.create();
        queryWrapper.where(SYS_PRODUCT_RECORD_SHIFT.SHIFT.eq(sysProductRecordShift.getShift()));
//        queryWrapper.select(SYS_PRODUCT_RECORD_SHIFT.ID,SYS_PRODUCT_RECORD_SHIFT.MACHINE_AREA,SYS_PRODUCT_RECORD_SHIFT.MACHINE_NAME,SYS_PRODUCT_RECORD_SHIFT.PRODUCT_DATE,SYS_PRODUCT_RECORD_SHIFT.SHIFT);
        queryWrapper.where(SYS_PRODUCT_RECORD_SHIFT.PRODUCT_DATE.eq(fromDateToString("yyyy-MM-dd", sysProductRecordShift.getProductDate())));
        queryWrapper.orderBy(SYS_PRODUCT_RECORD_SHIFT.MACHINE_NAME, true);
//        RelationManager.addIgnoreRelations("productInfo");
        List<SysProductRecordShift> sysProductRecordShiftList = this.sysProductRecordShiftService.getMapper().selectListWithRelationsByQuery(queryWrapper);
        List<SysProductRecordShift> productRecordShiftList = new ArrayList<>();
        for (SysProductRecordShift productRecordShift : sysProductRecordShiftList) {
//            queryWrapper = QueryWrapper.create();
//            LocalDate localDate = sysProductRecordShift.getProductDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
//            queryWrapper.where(SYS_PRODUCT_RECORD_SHIFT.SHIFT.eq(sysProductRecordShift.getShift()));
//            queryWrapper.where(SYS_PRODUCT_RECORD_SHIFT.MACHINE_NAME.eq(sysProductRecordShift.getMachineName()));
//            queryWrapper.where(SYS_PRODUCT_RECORD_SHIFT.PRODUCT_DATE.eq(localDate.minusDays(1)));
//            queryWrapper.where(SYS_PRODUCT_RECORD_SHIFT.NOW_TAIL_BOX_COUNT.gt(0));
//            queryWrapper.where(SYS_PRODUCT_RECORD_SHIFT.PRODUCT_ID.eq(productRecordShift.getProductId()));
//            queryWrapper.where(SYS_PRODUCT_RECORD_SHIFT.IS_ENTRY.eq(false));
//            queryWrapper.orderBy(SYS_PRODUCT_RECORD_SHIFT.MACHINE_NAME, true);
//            queryWrapper.orderBy(SYS_PRODUCT_RECORD_SHIFT.CREATE_TIME, false);
//            queryWrapper.limit(1);
//            SysProductRecordShift yesterdayProductRecordShift = this.sysProductRecordShiftService.getOne(queryWrapper);
//            if (yesterdayProductRecordShift != null) {
//                log.error("尾箱数：{}", JSONObject.toJSONString(yesterdayProductRecordShift));
//                productRecordShift.setLastTailBoxCount(yesterdayProductRecordShift.getNowTailBoxCount());
//            }
            log.error("生产记录：{}", productRecordShift);
            SysMachinePlc sysMachinePlc = productRecordShift.getSysMachinePlc();
            if (sysMachinePlc != null) {
                String lineManager = sysProductRecordShift.getLineManager();
                String lineManagerA = sysMachinePlc.getLineManagerA();
                String lineManagerB = sysMachinePlc.getLineManagerB();
                if (lineManagerA.contains(lineManager)) {
                    productRecordShift.setLineManager(lineManagerA);
                    productRecordShiftList.add(productRecordShift);
                } else if (lineManagerB.contains(lineManager)) {
                    productRecordShift.setLineManager(lineManagerB);
                    productRecordShiftList.add(productRecordShift);

                }
            }

        }
        return productRecordShiftList.isEmpty() ? ResultTool.fail() : ResultTool.success(productRecordShiftList);
    }

    /**
     * 根据主键获取详细信息。
     *
     * @param id 主键
     * @return 详情
     */
    @GetMapping("getInfo/{id}")
    public Result<?> getInfo(@PathVariable Serializable id) {
        return ResultTool.success(sysProductRecordShiftService.getMapper().selectOneWithRelationsById(id));
    }

    /**
     * 分页查询。
     *
     * @param page 分页对象
     * @return 分页对象
     */
    @GetMapping("page")
    public Page<SysProductRecordShift> page(Page<SysProductRecordShift> page) {
        return sysProductRecordShiftService.page(page);
    }
    @PostMapping("/getProductIdList")
    public Result<?> getProductIdList(@RequestBody SysProductRecordShift sysProductRecordShift) {
        QueryWrapper queryWrapper = QueryWrapper.create();
        queryWrapper.where(SYS_PRODUCT_RECORD_INTO.PRODUCT_DATE.between(sysProductRecordShift.getStartDate(), sysProductRecordShift.getEndDate()));
        if (sysProductRecordShift.getShift() != null) {
            queryWrapper.where(SYS_PRODUCT_RECORD_INTO.SHIFT.eq(sysProductRecordShift.getShift()));
        }
        queryWrapper.where(SYS_PRODUCT_RECORD_INTO.PRODUCT_ID.like(sysProductRecordShift.getProductIdQuery()));
        queryWrapper.select(distinct(SYS_PRODUCT_RECORD_INTO.PRODUCT_ID));
        queryWrapper.orderBy(SYS_PRODUCT_RECORD_INTO.PRODUCT_ID, true);
        List<SysProductRecordShift> productRecordIntoList = this.sysProductRecordShiftService.list(queryWrapper);
        log.error("SysSQL:{}", JSONObject.toJSONString(queryWrapper.toSQL()));
        return productRecordIntoList.isEmpty() ? ResultTool.fail() : ResultTool.success(productRecordIntoList);
    }

    @PostMapping("/getProductShiftDifferenceList")
    public Result<?> getProductDateIntoDifferenceList(@RequestBody SysProductRecordShift productRecordShift) {
        QueryWrapper queryWrapper = QueryWrapper.create();
        queryWrapper.where(SYS_PRODUCT_RECORD_SHIFT.PRODUCT_DATE.between(productRecordShift.getStartDate(), productRecordShift.getEndDate()));
        if (productRecordShift.getShift() != null) {
            queryWrapper.where(SYS_PRODUCT_RECORD_SHIFT.SHIFT.eq(productRecordShift.getShift()));
        }
        if (productRecordShift.getProductIds() != null) {
            if (productRecordShift.getProductIds().size() > 0) {
                queryWrapper.where(SYS_PRODUCT_RECORD_SHIFT.PRODUCT_ID.in((Object) productRecordShift.getProductIds()));
            }
        }

        queryWrapper.orderBy(SYS_PRODUCT_RECORD_SHIFT.MACHINE_NAME, true);
        queryWrapper.orderBy(SYS_PRODUCT_RECORD_SHIFT.PRODUCT_DATE, true);
//        queryWrapper.where(SYS_PRODUCT_RECORD_SHIFT.WORK_SHOP.eq("成型车间").or(SYS_PRODUCT_RECORD_SHIFT.WORK_SHOP.isNull()).or(SYS_PRODUCT_RECORD_SHIFT.WORK_SHOP.eq("")));
        queryWrapper.where(SYS_PRODUCT_RECORD_SHIFT.MACHINE_AREA.eq("A区域").or(SYS_PRODUCT_RECORD_SHIFT.MACHINE_AREA.eq("B区域").or(SYS_PRODUCT_RECORD_SHIFT.MACHINE_AREA.eq("C区域"))));
        queryWrapper.orderBy(SYS_PRODUCT_RECORD_SHIFT.SHIFT,false);
//        queryWrapper.where(SYS)
        RelationManager.addIgnoreRelations("productRecordShift", "sysMachinePlc");

        List<ProductRecordIntoModel> productRecordIntoList=this.sysProductRecordShiftService.getMapper().selectListWithRelationsByQueryAs(queryWrapper,ProductRecordIntoModel.class);
//        List<SysPr> productRecordIntoList = this.sysProductRecordShiftService.list(queryWrapper);
        return productRecordIntoList.isEmpty() ? ResultTool.fail() : ResultTool.success(productRecordIntoList);

    }

    @PostMapping("/getProductRecordShiftDataLabel")
    public Result<?> getProductRecordShiftDataLabel(@RequestBody SysProductRecordShift sysProductRecordShift) {
        List<DataLabel> dataLabelList = new ArrayList<>();
        QueryWrapper queryWrapper = QueryWrapper.create();
        queryWrapper.where(SYS_PRODUCT_RECORD_SHIFT.SHIFT.eq(sysProductRecordShift.getShift()));
        queryWrapper.select(SYS_PRODUCT_RECORD_SHIFT.ID, SYS_PRODUCT_RECORD_SHIFT.MACHINE_AREA, SYS_PRODUCT_RECORD_SHIFT.MACHINE_NAME,SYS_PRODUCT_RECORD_SHIFT.PRODUCT_ID, SYS_PRODUCT_RECORD_SHIFT.PRODUCT_DATE, SYS_PRODUCT_RECORD_SHIFT.SHIFT, SYS_PRODUCT_RECORD_SHIFT.WORK_PLAN_ID);
        queryWrapper.where(SYS_PRODUCT_RECORD_SHIFT.PRODUCT_DATE.eq(fromDateToString("yyyy-MM-dd", sysProductRecordShift.getProductDate())));
        queryWrapper.orderBy(SYS_PRODUCT_RECORD_SHIFT.MACHINE_NAME, true);
        queryWrapper.where(SYS_PRODUCT_RECORD_SHIFT.WORK_SHOP.eq("成型车间").or(SYS_PRODUCT_RECORD_SHIFT.WORK_SHOP.eq("").or(SYS_PRODUCT_RECORD_SHIFT.WORK_SHOP.isNull())));
        log.info("QSL:{}",queryWrapper.toSQL());
        String lineManager = sysProductRecordShift.getLineManager();
        RelationManager.addIgnoreRelations("workPlan");
        List<SysProductRecordShift> sysProductRecordShiftList = this.sysProductRecordShiftService.getMapper().selectListWithRelationsByQuery(queryWrapper).stream().filter(item -> item.getSysMachinePlc() != null).collect(Collectors.toList());
        sysProductRecordShiftList = sysProductRecordShiftList.stream().filter(item -> item.getSysMachinePlc().getLineManagerA().contains(lineManager) || item.getSysMachinePlc().getLineManagerB().contains(lineManager)).collect(Collectors.toList());

        if (CollectionUtils.isEmpty(sysProductRecordShiftList)) {
            return ResultTool.fail();
        }
        List<String> machineAreaList = sysProductRecordShiftList.stream().map(SysProductRecordShift::getMachineArea).distinct().collect(Collectors.toList());

        Map<String, List<SysProductRecordShift>> map = sysProductRecordShiftList.stream().collect(Collectors.groupingBy(SysProductRecordShift::getMachineArea));
        machineAreaList.forEach(item -> {
            List<DataLabel> dataLabelList1 = new ArrayList<>();
            List<SysProductRecordShift> productRecordShiftList = map.get(item);
            AtomicInteger index= new AtomicInteger();
            productRecordShiftList.forEach(record->{
                dataLabelList1.add(DataLabel.builder().parentIndex(index.get()).label(record.getMachineName()+"("+record.getProductId()+")").value(record.getId()).build());
                index.getAndIncrement();
            });
            dataLabelList.add(DataLabel.builder().label(item).value(item).children(dataLabelList1).build());
        });
        return ResultTool.success(dataLabelList);
    }

}
